package com.base.http

import okhttp3.Cookie
import okhttp3.CookieJar
import okhttp3.HttpUrl
import java.util.*

/**
 * 动态代理cookie
 */
object ICookieJar: CookieJar {
    private val cookieList: MutableList<Cookie> by lazy { ArrayList<Cookie>() }

    override fun saveFromResponse(url: HttpUrl?, cookies: List<Cookie>?) {
        if(cookies != null && cookies.isNotEmpty()) cookieList.addAll(cookies)
    }

    override fun loadForRequest(url: HttpUrl?): List<Cookie>? {
        val valid: MutableList<Cookie> = ArrayList()
        val invalid: MutableList<Cookie> = ArrayList()
        for (cookie in cookieList) {
            if (cookie.expiresAt() <= System.currentTimeMillis()) {
                invalid.add(cookie)
            } else if (cookie.matches(url)) {
                valid.add(cookie)
            }
        }
        cookieList.removeAll(invalid)
        return valid
    }
}